var list;
$(document).ready(function () {
    $('title')[0].innerHTML='客户列表';
     list= $('#List');
    $('.xh-datagrid-toolbar').parseToolbar();
    $('.xh-form').parseForm($('#bt_Form_Add, #bt_Form_Edit'));

    $btn_menu=$('#bt_list_menu').menubutton({
        iconCls: 'fa fa-bars',
        menu: '#mm'
    });
    
    list.initDataGrid(baseUrl + 'customer/getData').setSelectThenEnable(['bt_list_del','bt_list_manage','bt_list_swapPower'],[]);

    $('#select_province').combobox({
        onSelect:function (record) {
            if(record.value != '') {
                $('#select_city').combobox({
                    url: baseUrl + 'customer/getAreaById/' + record.value,
                    valueField: 'areaCode',
                    textField: 'areaName',
                    onSelect: function (record2) {
                        if(record2.areaCode != ''){
                            $('#select_county').combobox({
                                url: baseUrl + 'customer/getAreaById/' + record2.areaCode,
                                valueField: 'areaCode',
                                textField: 'areaName'
                            })
                        }else {
                            $('#select_county').combobox('setValue','');
                        }
                    }
                })
            }else {
                $('#select_city').combobox('setValue','');
                $('#select_county').combobox('setValue','');
            }
        }
    });

    $('#bt_list_swapPower').click(function () {
        if( xhExtra.buttonDisabled($(this))){
            return false;
        }
        swal({
            titleText: '客户交接',
            html:'<label style="width: 75px;">交接时间</label><input type="date" class="form-control" id="dateInput" style="display: inline;width: 300px;margin-bottom: 10px;"><br>' +
                '<label style="width: 75px;">交接人</label><select name="iUserId" class="form-control" id="iUserId" style="display: inline;width: 300px;"></select>' ,
            showCancelButton: true,
            cancelButtonText: '取消',
            confirmButtonText: '确认',
            showLoaderOnConfirm: true,
            onOpen:function () {
                var str = '<option value="">请选择</option>';
                $.each(market,function (id,text) {
                    str += '<option value="'+id+'">'+text+'</option>';
                });
                $('#iUserId').append(str).select2();
                $('#dateInput').val(xhTool.getNowDate(0));
            },
            preConfirm: function () {
                return new Promise(function (resolve, reject) {
                    var date   = $('#dateInput').val();
                    var userId = $('#iUserId').val();
                    if (!date || !userId) {
                        reject('注意信息填写完整！');
                    } else {
                        resolve();
                    }
                })
            },
            allowOutsideClick: true
        }).then(function () {
            var date   = $('#dateInput').val();
            var userId = $('#iUserId').val();
            var iCUIdArr = list.getDataGridSelectedFields('iCUId',true);
            xhExtra.ajaxRequest('customer/swapPower', {iCUIdArr:iCUIdArr,date:date,userId:userId},{},function (res) {
                window.top.xhTop.showSuccess(res.msg);
                list.dataGridReload();
            });
        }, function(dismiss) {});

    });

    /** 列表 **/
    $('#bt_list_add').click(function(){
        // $.overtFun.clickAddList(list);
        try{
            window.top.xhTop.createNewTab("新增客户信息",baseUrl+'customer/addCustomer',false);
        }catch (e){
            window.open(baseUrl+'customer/addCustomer');
        }
        // window.open(baseUrl+'customer/addCustomer');
        return false;
    });
    DataGrid.onLoadSuccess = function(){
        list.dataGridClear();
        var row = list.datagrid("getRows");
        for (var r = 0; r < row.length; r++)
        {
            if(row[r]['infoComplete'] != null){
                $('#indicatorContainer_'+row[r]['iCUId']).radialIndicator({
                    barColor: {
                        0: '#FF0000',
                        33: '#FF9900',
                        66: '#0066FF',
                        100: '#33CC33'
                    },
                    barWidth:2,
                    initValue : row[r]['infoComplete'],
                    percentage: true,
                    radius:15
                });
            }
        }
    };
    DataGrid.rowStyler = function(rowIndex, rowData){
        var year ='';
        if(rowData['tCoopDate'] != null){
           year = rowData['tCoopDate'].split('-')[0];
        }
        var myDate = new Date();
        if(year == myDate.getFullYear()){
            $('tr[datagrid-row-index="'+ rowIndex +'"]').find('td[field="tCoopDate"]').css('color', '#2baab1');
        }
    };

    xhTool.bindDocKeyDown($('#bt_list_search'));
    $('.xh-datagrid').on('click','[id^=file-]',function () {
        var iCUTId=$(this).attr("id").split("-")[1];
        var iBPPId=$(this).attr("id").split("-")[2];
        window.top.xhTop.createNewTab('流程计划',baseUrl+'../bpm/plan/planList?iBPPId='+iBPPId+'&iCUId='+iCUTId+'',true);

    });


    $($btn_menu.menubutton('options').menu).menu({
        onClick: function (item) {
            //item 的相关属性参见API中的menu
            //alert(item.text);
            if(item.text=='创建项目流程计划'){
                var $iCUId = list.getDataGridSelectedFields('iCUId');
                var $name = list.getDataGridSelectedFields('sSchoolName');
              //console.log($iCUId)
                if($iCUId==null || $iCUId==""){
                    window.top.swal('错误', '请先选择学校再发起创建!', 'error');
                    return false;
                }
                if(list.datagrid('getSelections').length>1){
                    window.top.swal('错误', '请选择一个学校', 'error');
                    return false;
                }

                $.ajax({
                    url:baseUrl+'../bpm/plan/beforeCreatePlan',
                    data:{iCUId:$iCUId},
                    type:'POST',
                    dataType:'json',
                    success:function (data) {
                        if(data['message']=='success'){
                            window.top.swal({
                                title: '当前学校在 '+data['data']['tCreateDate']+', 由 '+data['data']['sCreateUserName']+' 创建了流程计划！',
                                text: '确定要继续创建吗？' ,
                                type: 'warning',
                                showCancelButton: true,
                                confirmButtonText: '继续创建',
                                cancelButtonText: '查看'
                            }).then(function() {
                                window.top.xhTop.showModal({
                                    title:'创建项目流程计划',
                                    content:'<iframe src="bpm/plan/planForm?id='+$iCUId+'&name='+escape($name)+'" style="height: 130px;border-style: none;padding: 0px;width: 100%;"></iframe>',
                                    button:'提交'
                                });
                            }, function(dismiss) {
                                //  dismiss can be 'overlay', 'cancel', 'close', 'esc', 'timer'
                                if (dismiss === 'cancel') {
                                    window.top.xhTop.createNewTab('流程计划',baseUrl+'../bpm/plan/planList?iBPPId='+data['data']['iBPPId']+'&iCUId='+data['data']['iCUId']+'',true);
                                }
                            })
                        }else {
                            window.top.xhTop.showModal({
                                title:'创建项目流程计划',
                                content:'<iframe src="bpm/plan/planForm?id='+$iCUId+'&name='+escape($name)+'" style="height: 130px;border-style: none;padding: 0px;width: 100%;"></iframe>',
                                button:'提交'
                            });
                        }
                    },
                    error:function (data) {
                        console.log(data);
                    }
                });


            }

        }
    });
    $('#bt_list_del').click(function () {
        var ids = list.getDataGridSelectedFields('iCUId');
        $.overtFun.clickDelList(ids, baseUrl + 'customer/delData');
    });

    $('#bt_list_manage').click(function () {
       if( xhExtra.buttonDisabled($(this))){
           return false;
       }
        var iCUId = list.getDataGridSelectedFields('iCUId',true);
        if(iCUId.length > 1 ){
            $iCUId = list.getDataGridSelectedFields('iCUId',false);
            window.top.xhTop.showModal({
                title:'设置权限',
                content:'<iframe src="'+baseUrl+'customer/authManage?id='+$iCUId+'&openType=double" style="height: 500px;border-style: none;padding: 0px;width: 100%;"></iframe>',
                size: 'md',
                button:'提交'
            });
        }else { //单个
            $iCUId = list.getDataGridSelectedFields('iCUId',false);
            window.top.xhTop.showModal({
                title:'设置权限',
                content:'<iframe src="'+baseUrl+'customer/authManage?id='+$iCUId+'" style="height: 500px;border-style: none;padding: 0px;width: 100%;"></iframe>',
                size: 'lg',
            });
        }
        // window.top.xhTop.createNewTab('客户权限管理',baseUrl+'customer/authManage?id='+$iCUId,true);
    });

    $('#excel_export').click(function () {
        var key=xhExtra.getValue($('#list_search'));  //$('.textbox-value')[0].value
        var select_type=xhExtra.getValue($('#select_type'));
        var select_agree=xhExtra.getValue($('#select_agree'));
        var select_group=xhExtra.getValue($('#select_group'));
        var select_province = $('#select_province').combobox('getText');
        var select_city = $('#select_city').combobox('getText');
        var select_county = $('#select_county').combobox('getText');
        window.open(baseUrl+'customer/exportCustomerList?key='+key+'&iType='+select_type+'&agree='+select_agree+'&group='+select_group+
            '&province='+select_province+'&city='+select_city+'&county='+select_county);
        $('#bt_list_search').click();
    });

    $('#bt_list_export_plan').click(function () {
        var key=xhExtra.getValue($('#list_search'));  //$('.textbox-value')[0].value
        var select_type=xhExtra.getValue($('#select_type'));
        var select_agree=xhExtra.getValue($('#select_agree'));
        var select_group=xhExtra.getValue($('#select_group'));
        var select_province = $('#select_province').combobox('getText');
        var select_city = $('#select_city').combobox('getText');
        var select_county = $('#select_county').combobox('getText');
        window.open(baseUrl+'customer/exportCustomerPlan?key='+key+'&iType='+select_type+'&agree='+select_agree+'&group='+select_group+
        '&province='+select_province+'&city='+select_city+'&county='+select_county);
        $('#bt_list_search').click();
    });
 
    $('#bt_list_search').click(function () {
        var key=xhExtra.getValue($('#list_search'));  //$('.textbox-value')[0].value
        var select_type=xhExtra.getValue($('#select_type'));
        var select_agree=xhExtra.getValue($('#select_agree'));
        var select_group=xhExtra.getValue($('#select_group'));
        // console.log(xhExtra.getValue($('#select_group')));
        var select_province = $('#select_province').combobox('getText');
        var select_city = $('#select_city').combobox('getText');
        var select_county = $('#select_county').combobox('getText');
        list.addDataGridParams({key:key,iType:select_type,agree:select_agree,group:select_group,
            province:select_province,city:select_city,county:select_county});
        //list.initDataGrid(baseUrl + 'customer/searchData?key='+key).setSelectThenEnable(['bt_List_Del']);
    });


        DataGrid.onDblClickRow = function(rowIndex, rowData){

            window.frames['customer'].document.location.href=baseUrl+'customer/customerTab?iCUId='+rowData.iCUId;
            $('#xhGrade').hide();
            $('#customerTab').show();

         
            return false;
        };



    /** 表单 **/
    // $('#bt_Form_Add, #bt_Form_Edit').click(function () {
    //     $.overtFun.clickSubmitForm();
    // });
    // $('#bt_Form_Back').click(function () {
    //     $.overtFun.clickBackForm();
    // });
    // $('#bt_Form_Reset').click(function () {
    //     $.overtFun.clickResetForm();
    // });
});

function loadWindow(target) {
    console.log($(target));
    alert('aaa');
    // $(target).select2();

}